import React from "react";
import BaseScreen from "./BaseScreen";
import ProgressView from "../view/ProgressView";
import { Actions, NameSpace } from "../model/taskModel";
import { connect } from "react-redux";
import styles from "../css/home.module.css";
import { locationTo } from "../utils/LocationUtil";
import * as locations from "../const/locations";
import { MyButton } from "../view/MyButton";
import Config from "../Config";
import Carousel from "../view/carousel";
import { TaskList } from "../const/datas"
import { getTasks } from '../service/TaskService';
import { notice } from '../service/newsService'
import { getTOKEN, setInfo } from '../utils/StorageUtil'
import { HintDialog } from '../view/Dialog'
import { NewsImg } from '../const/imgs'
import Scroll from './components/Bscroll/index'
import { resolve } from "path";
import UploadImgs from './components/UploadImgs'
import {NOTASK} from './components/Default'

class HomeScreen extends BaseScreen {
  componentDidMount() {
    document.title = "首页"
    this.getTaskList({
      status: getStatus(this.state.taskTabIndex),
      current_page: this.CURRENT_PAGE,
      per_page: this.PER_PAGE
    })
    this.getNewsList()
  }

  constructor(props) {
    super(props);
    this.CURRENT_PAGE = 1;
    this.PER_PAGE = 5;
    this.state = {
      taskTabIndex: this.props.taskTabIndex,
      TaskList: [],
      newsList: [],
      loading:false
    };
  }
  getNewsList = () => {
    notice({
      token: getTOKEN(),
    })
    .then(
      res =>{
        if(res.error_code === 0){
          const data = res.data.data
          this.setState({
            newsList: [...data,data[0]]
          })
        }
      }
    )
    .catch(
      err => {
        console.log(err)
      }
    )
  }
  // 获取任务列表
  getTaskList = (params) => {
    const that = this
    const TaskList = params.isReFresh?[]:this.state.TaskList
    
    this.setState({ loading: true });
    getTasks({
      token: getTOKEN(),
      ...params
    })
      .then(
        res => {
          // this.showMsgDialog(res.msg)
          
        this.setState({ loading: false });
          this.setState({
            TaskList: [...TaskList, ...res.data.data],
            isShowMore:res.data.data.length=== this.PER_PAGE
          })
          that.CURRENT_PAGE++;
        }
      )
      .catch(
        err => {
          console.log(err)
        }
      )
  }
  navigate = (e) => {
    this.setState({
      taskTabIndex: e
    })
    this.props.taskTab({
      taskTabIndex: e
    })

    this.CURRENT_PAGE = 1;
    this.getTaskList({
      status: getStatus(e),
      current_page: this.CURRENT_PAGE,
      per_page: this.PER_PAGE,
      isReFresh:true
    })

  }

  selectItem = (e,expiredDays) => {
    this.props.selectItem({...e,expiredDays:expiredDays})
    setInfo('ids',{
      taskId: e.id,
      caseId: e.case_id,
      expiredDays:expiredDays.toString()
    })
    locationTo(locations.TASKDETAIL)
  }
  pullingUp = () => {
    const that = this

    this.getTaskList({
      status: getStatus(this.state.taskTabIndex),
      current_page: this.CURRENT_PAGE,
      per_page: this.PER_PAGE
    })
  }
  render() {
    const {
      TaskList,
      hasMore,
      isShowMore,
      newsList,
      loading
    } = this.state
    const taskList = TaskList.map((item, index) => {
      return (
        <TaskListItem
          key={index}
          item={item}
          selectItem={this.selectItem}
          taskTabIndex={this.state.taskTabIndex}
        />
      )
    })
    return (
      <div className={styles["home"]}>
        <Navigator click={this.navigate} taskTabIndex={this.state.taskTabIndex} />
        <div className={styles['container']}>
          {/* {this.state.msg} */}
          {/* {this.state.data} */}
          <Scroll
            ref='scroll'
            click={true}
            bounce={true}
            pullUpLoad={true}
            pullUpLoadMoreData={this.pullingUp}
            isPullUpTipHide={true}
            isShowMore={isShowMore}
          >
            <News list={newsList}/>
            {/* <UploadImgs/> */}
            <div className={styles['content1']} ref='content' >
            {!taskList.length>0&&<NOTASK des="暂无相关任务"/>}
              {taskList}
            </div>
          </Scroll>
        </div>
        <HintDialog
          ref="dialog"
          style={{
            color: "#fff"
          }}
          visibility={this.state.alertMsg !== ""}
          content={this.state.alertMsg}
          operateText="确定"
        // operateClick={this.abandon}
        />
          <ProgressView visibility={loading} mode={ProgressView.MODE_MEDIUM} />
        
      </div>
    );
  }
}



function getStatus(e) {
  let status

  switch (e) {
    case 0:
      status = 1;
      break;
    case 1:
      status = 4;
      break;
    case 2:
      status = '2,3';
      break;
    default:
      status = 1;
  }
  return status
}
const TaskListItem = ({
  item,
  item: {
    id, // 催客任务ID
    init_debt, // 初始债务金额（分）
    overdue_day, // 当前逾期天数
    expired_time, // 催收任务过期时间
    repay_amount, // 已还款金额（分）
    received_rwd, // 已获得奖金（分）
    commision_case_no, // 案件编号
    usual_addr_detail, // 常住地详情
    reward_ratio, // 奖金比例
    status, // 任务状态
  },
  selectItem,
  taskTabIndex
}) => {
  // 剩余天数
  const expiredDays = Math.round((new Date(expired_time).getTime() - new Date().getTime()) / (24 * 60 * 60 * 1000))
  return (
    <div
      onClick={() => selectItem(item,expiredDays)}
      className={styles["task_item"]}
      style={{ color: Config.fontColor }}
    >
      <div className={styles["task_head"]}>
        <div className={styles["task_code"]}>
          案件编号：<span style={{ color: Config.BaseColor }}>{commision_case_no}</span>
        </div>
        <div className={styles["task_state"]}>
          {parseInt(status,10) === 1 && <span>剩余{expiredDays}天</span>}
          {parseInt(status,10) === 4 && <span>已到期</span>}
          {parseInt(status,10) === 2 && <span>已放弃</span>}
          {parseInt(status,10) === 3 && <span>已取消</span>}
        </div>
      </div>

      {taskTabIndex === 0 &&
        <div className={styles["task_data"]}>
          <ItemCenter name='总额' value={init_debt + '元'} />
          <ItemCenter name='逾期' value={overdue_day + '天'} />
          <ItemCenter name='奖金' value={reward_ratio / 100 + '%'} />
        </div>
      }
      {taskTabIndex === 1 &&
        <div className={styles["task_data"]}>
          <ItemCenter name='总额' value={init_debt + '元'} />
          <ItemCenter name='回款金额' value={repay_amount + '元'} />
          <ItemCenter name='奖金' value={received_rwd + '元'} />
        </div>
      }
      {taskTabIndex === 2 &&
        <div className={styles["task_data"]}>
          <ItemCenter name='总额' value={init_debt + '元'} />
          <ItemCenter name='逾期' value={overdue_day + '天'} />
          <ItemCenter name='奖金' value={reward_ratio / 100 + '%'} />
        </div>
      }

      <div className={styles["task_foot"]}>
        <div className={styles["task_addr"]} style={{ color: Config.fontColor2 }}>
          {usual_addr_detail}
        </div>
      </div>
    </div>
  )
}

const ItemCenter = ({ name, value }) => {
  return (

    <div className={styles["task_cell"]}>
      <div className={styles["task_data_key"]} style={{ color: Config.fontColor1 }}>
        {name}
      </div>
      <div className={styles["task_data_value"]}>
        {value}
      </div>
    </div>
  )
}

const Navigator = ({ click, taskTabIndex }) => {
  return (
    <div className={styles['nav_wrapper']}>
      {
        navList.map((item, index) => {
          return (<div
            key={item.name}
            onClick={() => { click(index) }}
            className={styles['nav_item']}
            style={taskTabIndex === index ? selectedStyle : {}}
          >
              <div style={{
              fontSize:'26px',
              transform: 'scale(0.5)',
              whiteSpace:'nowrap',
              width:'80px',
              textAlign:'center'
            }}>
            {item.name}
          </div>
          </div>)
        })
      }

    </div>
  )
}
const News = ({ list,navigateTo }) => {
  return (
    <div className={styles["news_wrapper"]} onClick={()=>{
      setInfo('newsType',1)
      locationTo(locations.TaskNews)
      }}>
      <img className={styles["news_icon"]} src={NewsImg.GGH} />
      <Carousel
        list={list}
        style={{
          height: 28,
          flex: 1
        }}
        transform="Y"
        Duration="0.5"
        TimingFunction="linear"
        start="top"
      />
    </div>
  );
};

const navList = [{
  name: '催收中'
},
{
  name: '已结束'
},
{
  name: '已中断'
}]
const selectedStyle = {
  color: "#fff",
  background: Config.BaseColor
}
const newsList = [
  {
    id: 1,
    text: "恭喜花锅锅成功借款10000元"
  },
  {
    id: 2,
    text: "恭喜花锅锅成功借款30000元"
  },
  {
    id: 3,
    text: "恭喜花锅锅成功借款50000元"
  },
  {
    id: 1,
    text: "恭喜花锅锅成功借款10000元"
  }
];



const mapStateToProps = state => {
  return {
    ...state[NameSpace]
  };
};

const mapDispatchToProps = dispatch => {
  return {
    selectItem(item) {
      let params = {
        taskId: item.id,
        caseId: item.case_id,
        expiredDays:item.expiredDays
      };
      dispatch(Actions.actionSelectId(params));
    },
    taskTab(item) {
      let params = {
        taskTabIndex: item.taskTabIndex
      };
      dispatch(Actions.actionTaskTab(params));
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
// export default HomeScreen;
